package com.etrans.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 文件或者字节流转码
 * 
 * @author 劳
 * @version 1.0
 * @since 2015-12-10
 * description
 * <p>创建类-2015-12-10</p> 
 */
@SuppressWarnings("restriction")
public class FileCode {
	
	/**
     * <p>将文件转成base64 字符串</p>
     * @param path 文件路径
     * @return
     * @throws Exception
     */
	public static String encodeBase64File(byte[] bytes) throws Exception {
        return new BASE64Encoder().encode(bytes);
    }	
	
	/**
     * <p>将文件转成base64 字符串</p>
     * @param path 文件路径
     * @return
     * @throws Exception
     */
	public static String encodeBase64File(InputStream inputStream) throws Exception {
		int byteLength = inputStream.available();
        byte[] buffer = new byte[byteLength];
        inputStream.read(buffer);
        inputStream.close();
        return new BASE64Encoder().encode(buffer);
    }	
	
	/**
     * <p>将文件转成base64 字符串</p>
     * @param path 文件路径
     * @return
     * @throws Exception
     */
	public static String encodeBase64File(String path) throws Exception {
        File  file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }
	
    /**
     * <p>将base64字符解码保存文件</p>
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code,String targetPath) throws Exception {
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }
    
    /**
     * <p>将base64字符保存文本文件</p>
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void toFile(String base64Code,String targetPath) throws Exception {
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }
    
    public static void main(String[] args) {
        try {
//            String base64Code =encodeBase64File("D:\\谷歌下载目录\\132145yj3ftco39t3tfrsn.jpg");
            FileInputStream fileInputStream = new FileInputStream(new File("D:\\谷歌下载目录\\132145yj3ftco39t3tfrsn.jpg"));
            String base64Code =  encodeBase64File(fileInputStream);
            System.out.println(base64Code);
            decoderBase64File(base64Code, "D:\\谷歌下载目录\\test.jpg");
            //toFile(base64Code, "D:\\three.txt");            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
